package com.sinping.qh.service.admin.noticebook.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.domain.common.UploadImage;
import com.sinping.qh.domain.common.UploadImageBase64Bean;
import com.sinping.qh.domain.lab.LabInspectItemRelationDomain;
import com.sinping.qh.domain.lab.LabInspectItemTreeDomain;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.noticebook.NoticeBookAuditDomain;
import com.sinping.qh.domain.noticebook.NoticeBookDomain;
import com.sinping.qh.domain.records.CheckRecord;
import com.sinping.qh.domain.records.HiddendangerRecord;
import com.sinping.qh.domain.records.RectifyReviewDomain;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.domain.user.UserLaboratory;
import com.sinping.qh.dto.admin.lab.LaboratoryDto;
import com.sinping.qh.dto.admin.noticebook.*;
import com.sinping.qh.dto.admin.record.HiddendangerRecordDto;
import com.sinping.qh.dto.admin.record.RectifyReviewDto;
import com.sinping.qh.dto.admin.user.MessageInfoDto;
import com.sinping.qh.dto.auth.UserSessionDTO;
import com.sinping.qh.dto.common.CommonDTO;
import com.sinping.qh.dto.common.ICommonDTO;
import com.sinping.qh.query.notice.NoticeBookQuery;
import com.sinping.qh.repository.mongo.lab.LabInspectItemRelationRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemTreeRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.noticebook.NoticeBookAuditRepository;
import com.sinping.qh.repository.mongo.noticebook.NoticeBookRepository;
import com.sinping.qh.repository.mongo.records.CheckRecordsRepository;
import com.sinping.qh.repository.mongo.records.HiddenDangerRecordRepository;
import com.sinping.qh.repository.mongo.records.impl.RectifyReviewRepositoryImpl;
import com.sinping.qh.repository.mongo.user.UserInfoRepository;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.impl.IAddorEditUserServiceImpl;
import com.sinping.qh.service.admin.noticebook.INoticeBookService;
import com.sinping.qh.service.app.MessageInfo.impl.MessageInfoImpl;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.service.common.FileManagerService;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.number.RandomUtil;
import com.sinping.qh.utils.time.DateFormatUtil;
import com.sinping.qh.utils.word.Base64Util;
import com.sinping.qh.utils.word.DocumentHandler;
import com.sinping.qh.utils.worddocx.WordTools;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author jiahuaiqing
 * @create 2018/5/30
 */
@Service
public class NoticeBookServiceImpl implements INoticeBookService {

    private final static Logger log = LoggerFactory.getLogger(NoticeBookServiceImpl.class);

    @Value(value = "${qh.upload.filePath}")
    private String filePath;
    @Value(value = "${qh.upload.urlPath}")
    private String urlPath;

    @Autowired
    MongoManager mongoManager;

    @Autowired
    private NoticeBookRepository noticeBookRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private NoticeBookAuditRepository noticeBookAuditRepository;

    @Autowired
    private HiddenDangerRecordRepository hiddenDangerRecordRepository;

    @Qualifier("sessionServiceRedisImpl")
    @Autowired
    private ISessionService iSessionService;

    @Autowired
    private FileManagerService commonService;

    @Autowired
    private CheckRecordsRepository checkRecordsRepository;

    @Autowired
    private RectifyReviewRepositoryImpl rectifyReviewRepositoryImpl;

    @Autowired
    private LaboratoryRepository laboratoryRepository;

    @Autowired
    private LabInspectItemRelationRepository labInspectItemRelationRepository;

    @Autowired
    LabInspectItemTreeRepository labInspectItemTreeRepository;

    @Autowired
    MessageInfoImpl messageInfo;

    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;
    @Autowired
    IAddorEditUserServiceImpl iAddorEditUserServiceImpl;

    /**
     * 生成通知书记录
     *
     * @param request
     * @param noticeBookDto
     * @return
     */
    @Override
    public ResDto addNoticeBook(HttpServletRequest request, NoticeBookReturnDto noticeBookDto) {
        String token = request.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "用户未登录");
        }
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {
            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }
        UserInfo userInfo = null;
        if (StringUtils.isNotBlank(userSessionDTO.getId())) {
            userInfo = userInfoRepository.findOne(userSessionDTO.getId());
            if (userInfo == null) {
                return new ResDto(Const.SERVER_ERROR, "创建人不存在");
            }
        }

        List<String> hiddenDangerIds = noticeBookDto.getHiddenDangerIds();
        String noticeReceiveUnitId = noticeBookDto.getNoticeReceiveUnitId();
        for (String hiddenDangerId : hiddenDangerIds) {
            HiddendangerRecord one = hiddenDangerRecordRepository.findOne(hiddenDangerId);
            if (!noticeReceiveUnitId.equals(one.getCheckUnitId())) {
                return new ResDto(Const.SERVER_ERROR, "隐患记录不属于同一个院系，请重新选择");
            }
        }

        //生成通知书编号 AQZG+yyyyMMdd+三位数字
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(calendar.getTime());
        String dateTimeNew = dateTime.replace("-", "");
        int nextInt = RandomUtil.nextInt(1000, 10000);
        String noticeNO = "AQZG" + dateTimeNew + nextInt;

        try {
            NoticeBookDomain noticeBookDomain = BeanMapper.map(noticeBookDto, NoticeBookDomain.class);
            noticeBookDomain.setId(IdGenerator.uuid2());
            noticeBookDomain.setNoticeNo(noticeNO);
            noticeBookDomain.setNoticeStatus("0");
            noticeBookDomain.setCreateUserId(userSessionDTO.getId());
            noticeBookDomain.setCreateUserName(userInfo.getFullName());
            //注意：这个时间
            //noticeBookDomain.setNoticeSendDate(new Date());
            noticeBookDomain.setGmtCreated(new Date());
            noticeBookDomain.setGmtModified(new Date());

            noticeBookRepository.save(noticeBookDomain);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("通知书生成成功");
            return resDto;
        } catch (Exception e) {
            log.error("数据解析异常{}", e);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.SERVER_ERROR);
            resDto.setMsg("数据解析异常");
            return resDto;
        }
    }

    /**
     * 通知书是根据配置的院系来查看
     *
     * @param page
     * @param commonDTO
     * @return
     */
    @Override
    public ResDto noticeBookFrontPage(FrontPage page, ICommonDTO commonDTO) {

        try {
            //msg->FrontPage(对象)->condition(Map)->Json->Dto(实体)->Query->用mongoManage.findPage查询
            Integer pageSize = page.getSize();
            Integer pageNum = page.getPage();
            NoticeBookQuery noticeBookQuery;
            //2.Map conditionMap
            Map<String, Object> conditionMap = page.getCondition();
            if (null == conditionMap || conditionMap.isEmpty()) {
                //return new ResDto(Const.PARAM_ERROR, "条件参数为空或有不正确的数据格式");
                //查询所有的记录
                //5.得到 NoticeBookQuery
                noticeBookQuery = new NoticeBookQuery();
            } else {
                //3.Map conditionMap=>String conditionJson
                String conditionJson = JsonMapper.defaultMapper().toJson(conditionMap);
                //4.String conditionJson=> NoticeBookDto dto
                NoticeBookDto dto = JsonMapper.defaultMapper().fromJson(conditionJson, NoticeBookDto.class);

                /**处理开始时间和结束时间**/
                if (null != dto.getNoticeSendDateStart()) {
                    String startDate = DateFormatUtil.formatDate("yyyy-MM-dd 00:00:00",
                            dto.getNoticeSendDateStart());
                    Date newStartDate = DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND,
                            startDate);
                    dto.setNoticeSendDateStart(newStartDate);
                }

                if (null != dto.getNoticeSendDateEnd()) {
                    String endDate = DateFormatUtil.formatDate("yyyy-MM-dd 23:59:59",
                            dto.getNoticeSendDateEnd());
                    Date newEndDate = DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND,
                            endDate);
                    dto.setNoticeSendDateEnd(newEndDate);
                }
                /**处理开始时间和结束时间**/
                //5.NoticeBookDto dto=> NoticeBookQuery noticeBookQuery
                noticeBookQuery = BeanMapper.map(dto, NoticeBookQuery.class);
            }
            //定义一个多条件的查询参数
            UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(((CommonDTO) commonDTO).getToken());
            List<String> units = Lists.newArrayList();
            if (userSessionDTO == null) {
                return new ResDto(Const.UNAUTHORIZED, "token异常,请重新登陆");
            }
            List<String> userManagerUnitIdList = iAddorEditUserServiceImpl.getUserManagerUnitIdOrLabIdList(userSessionDTO.getId(), CommonDbConst.USER_MANAGER_UNIT);
            List<String> userManagerLabIdList = iAddorEditUserServiceImpl.getUserManagerUnitIdOrLabIdList(userSessionDTO.getId(), CommonDbConst.USER_MANAGER_LAB);


            for (String id : userManagerUnitIdList) {
                units.add(id);
            }
            List<String> labs = userManagerLabIdList;

            //根据实验室来查询负责的院系
            for (String labId : labs) {

                LaboratoryDomain laboratoryDomain =
                        laboratoryRepository.findByIdAndStatus(labId, CommonDbConst.DB_DELETE_NORMAL);
                if (laboratoryDomain != null && !units.contains(laboratoryDomain.getUnitId())) {
                    units.add(laboratoryDomain.getUnitId());
                }

            }

            if (units.size() > 0) {
                if (StringUtils.isNotBlank(noticeBookQuery.getNoticeReceiveUnitId())) {
                    //有权限
                    if (units.contains(noticeBookQuery.getNoticeReceiveUnitId())) {

                    } else {
                        //无权限
                        noticeBookQuery.setNoticeReceiveUnitId("");
                    }

                } else {
                    noticeBookQuery.setNoticeReceiveUnitIdList(units);
                }

            }
            //设置查询条件
            Pageable pageRequest = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "gmt_created"));
            //6.用MongoManager去查询的数据
            Page<NoticeBookDomain> pageResult = mongoManager.findPage(noticeBookQuery, pageRequest, NoticeBookDomain.class);

            //7.把查询结果放到FrontPage中返回到接口
            /****方法一**start***/
            /**
             //查询的数据中获取-总页数
             int totalPages = pageResult.getTotalPages();
             //查询的数据中获取-总记录数
             long totalElements = pageResult.getTotalElements();
             //查询的数据中获取-内容集合(数据库中的内容集合--实体类：NoticeBookDomain)
             List<NoticeBookDomain> content = pageResult.getContent();

             //(数据库中的内容集合--实体类：NoticeBookDomain)=>(接口中的要显示的内容集合--实体类：NoticeBookDto)
             List<NoticeBookDto> noticeBookDtoList = BeanMapper.mapList(content, NoticeBookDto.class);

             //重新定义FrontPage(),要返回到接口中去
             FrontPage resultFrontPage = new FrontPage();
             resultFrontPage.setTotal((int)totalElements);
             resultFrontPage.setPage(pageNum);
             resultFrontPage.setRecords(noticeBookDtoList);
             resultFrontPage.setPages(totalPages);

             //设置返回的结果到ResDto
             ResDto resDto = new ResDto(ConstEum.SUCCESS);
             resDto.setDatas(JsonMapper.defaultMapper().toJson(resultFrontPage));
             **/
            /****方法一**end***/
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            //给pdf的路径添加了urlPath
            //ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto, pageResult, NoticeBookReturnDto.class, page);
            List<NoticeBookDomain> contentList = pageResult.getContent();
            List<NoticeBookDomain> copyApiOrders = new ArrayList<>();
            for (NoticeBookDomain domain : contentList) {
                if (StringUtils.isNotBlank(domain.getNoticeAttachPath())) {
                    domain.setNoticeAttachPath(urlPath + domain.getNoticeAttachPath());
                }
                copyApiOrders.add(domain);
            }
            List apiOrders = BeanMapper.mapList(copyApiOrders, NoticeBookReturnDto.class);
            long totalPages = pageResult.getTotalPages();
            int currentPage = page.getPage();
            FrontPage frontPage = new FrontPage();
            frontPage.setPage(currentPage);
            frontPage.setTotal((int) pageResult.getTotalElements());
            frontPage.setPages((int) totalPages);
            frontPage.setRecords(apiOrders);
            resDto.setDatas(JsonMapper.defaultMapper().toJson(frontPage));
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("分页数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "分页数据处理异常");
        }
    }

    @Override
    public ResDto updateNoticeBook(HttpServletRequest request, NoticeBookReturnDto noticeBookDto) {

        try {
            String token = request.getHeader(Const.TOKEN_NAME);
            UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
            if (userSessionDTO == null) {
                return new ResDto(Const.PARAM_ERROR, "用户未登录");
            }
            //验证参数
            if (StringUtils.isBlank(userSessionDTO.getId())) {
                return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
            }

            if (!StringUtils.isNotBlank(noticeBookDto.getId())) {
                return new ResDto(Const.FORMAT_ERROR, "通知书id不能为空");
            }
            NoticeBookDomain noticeBookdb = null;
            if (StringUtils.isNotBlank(noticeBookDto.getId())) {
                noticeBookdb = noticeBookRepository.findOne(noticeBookDto.getId());
                if (noticeBookdb == null) {
                    return new ResDto(Const.SERVER_ERROR, "通知书id不存在");
                }
            }
            //添加修改内容到noticeBookdb中去
            noticeBookdb.setNoticeSendDepart(noticeBookDto.getNoticeSendDepart());
            noticeBookdb.setNoticeLeader(noticeBookDto.getNoticeLeader());
            noticeBookdb.setNoticeCheckDesc(noticeBookDto.getNoticeCheckDesc());
            noticeBookdb.setNoticeCheckRequirement(noticeBookDto.getNoticeCheckRequirement());
            noticeBookdb.setHiddenDangerIds(noticeBookDto.getHiddenDangerIds());
            noticeBookdb.setGmtModified(new Date());
            //审核退回的状态修改为待审核
            if (noticeBookdb.getNoticeStatus().equals("2")) {
                noticeBookdb.setNoticeStatus("0");
            }

            NoticeBookDomain save = noticeBookRepository.save(noticeBookdb);
            if (save == null) {
                new ResDto(Const.SERVER_ERROR, "通知书修改失败");
            }
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setMsg("通知书修改成功");
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "数据处理异常");
        }
    }

    @Override
    public ResDto updateNoticeBookStatus(HttpServletRequest request, NoticeBookReturnDto noticeBookDto) {
        String token = request.getHeader(Const.TOKEN_NAME);
        UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
        if (userSessionDTO == null) {
            return new ResDto(Const.PARAM_ERROR, "用户未登录");
        }
        //验证参数
        if (StringUtils.isBlank(userSessionDTO.getId())) {
            return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
        }

        NoticeBookDomain noticeBookdb = null;
        if (StringUtils.isNotBlank(noticeBookDto.getNoticeNo())) {
            noticeBookdb = noticeBookRepository.findByNoticeNo(noticeBookDto.getNoticeNo());
            if (noticeBookdb == null) {
                return new ResDto(Const.DATA_ERROR, "通知书编号不存在");
            }
        }
        try {
            if (StringUtils.isNotBlank(noticeBookDto.getNoticeStatus())) {
                noticeBookdb.setNoticeStatus(noticeBookDto.getNoticeStatus());
            }
            if (StringUtils.isNotBlank(noticeBookDto.getNoticeCaseStatus())) {
                noticeBookdb.setNoticeCaseStatus(noticeBookDto.getNoticeCaseStatus());
            }
            //表示点击了下发按钮
            if (noticeBookDto.getNoticeStatus().equals("3") && noticeBookDto.getNoticeCaseStatus().equals("0")) {
                //设置下发日期
                noticeBookdb.setNoticeSendDate(new Date());
            }
            NoticeBookDomain save = noticeBookRepository.save(noticeBookdb);
            if (save == null) {
                return new ResDto(Const.SERVER_ERROR, "通知书状态更新失败");
            }
            //表示点击了下发按钮：第一步修改状态并设置下发时间，第二步生成pdf并保存路径地址，第三步：发送系统消息
            if (save.getNoticeStatus().equals("3") && save.getNoticeCaseStatus().equals("0")) {
                //生成pdf,并把文件地址保存到通知书表中
                String id = saveNoticePdf(save.getId());
                //验证非空
                if (StringUtils.isBlank(id)) {
                    return null;
                }
                //调用下载文件service
                String url = commonService.getFileOrImageUrlById(id);
                if (!StringUtils.isNotBlank(url)) {
                    return new ResDto(Const.SERVER_ERROR, "获取文件地址为空");
                }

                //保存pdf路径到通知书表中的notice_attach_path
                noticeBookdb.setNoticeAttachPath(url);
                NoticeBookDomain savepdfpath = noticeBookRepository.save(noticeBookdb);
                if (savepdfpath == null) {
                    return new ResDto(Const.SERVER_ERROR, "保存pdf地址失败!");
                }
                //todo 发送系统消息
                String noticeNoBiaoHao = noticeBookdb.getNoticeNo();
                List<UserLaboratory> userLabLists = userLaboratoryRepository.findByManagerUnitIdAndStatus(noticeBookdb.getNoticeReceiveUnitId(), "0");
                ArrayList<String> ReceiveIdList = new ArrayList<>();
                for (UserLaboratory userLab : userLabLists) {
                    if (!ReceiveIdList.contains(userLab.getUserId())) {
                        ReceiveIdList.add(userLab.getUserId());
                    }
                }
                MessageInfoDto messageInfoDto = new MessageInfoDto();
                messageInfoDto.setTitle("整改通知书" + noticeNoBiaoHao);
                String sendDate = DateFormatUtil.formatDate("yyyy-MM-dd", new Date());
                messageInfoDto.setContent(noticeBookdb.getNoticeSendDepart() + "于"
                        + sendDate + "向"
                        + noticeBookdb.getNoticeReceiveUnitName()
                        + "下发整改通知书，通知书编号" + noticeNoBiaoHao);
                messageInfoDto.setLinkUrl(noticeBookdb.getNoticeAttachPath());
                //1 消息 0通知
                messageInfoDto.setType("1");
                messageInfoDto.setReceiveIds(ReceiveIdList);
                messageInfo.addMessageInfo(request, messageInfoDto);
            }
            return new ResDto(Const.SUCCESS, "通知书状态更新成功");
        } catch (Exception e) {
            log.error("对象转化异常");
            return new ResDto(Const.SERVER_ERROR, "数据解析异常");
        }

    }

    /**
     * 获取通知书详情
     *
     * @param id
     * @return
     */
    @Override
    public ResDto getNoticeBookById(String id) {
        NoticeBookDomain noticeBookdb = null;
        if (StringUtils.isNotBlank(id)) {
            noticeBookdb = noticeBookRepository.findOne(id);
            if (noticeBookdb == null) {
                return new ResDto(Const.DATA_ERROR, "id不存在");
            }
        }

        try {
            NoticeBookDetailDto nBDetailDto = new NoticeBookDetailDto();
            //基本信息
            NoticeBookReturnDto noticeBookDto = BeanMapper.map(noticeBookdb, NoticeBookReturnDto.class);
            String noticeAttachPath = noticeBookDto.getNoticeAttachPath();
            noticeBookDto.setNoticeAttachPath(urlPath + noticeAttachPath);
            nBDetailDto.setNoticeBookDto(noticeBookDto);
            //隐患记录
            List<String> hiddenDangerIds = noticeBookdb.getHiddenDangerIds();
            if (null != hiddenDangerIds && !hiddenDangerIds.isEmpty()) {
                Iterable<HiddendangerRecord> all = hiddenDangerRecordRepository.findAll(hiddenDangerIds);
                List<HiddendangerRecordDto> hiddendangerRecordDtoLists = BeanMapper.mapList(all, HiddendangerRecordDto.class);
                nBDetailDto.setHiddenDangerRecordList(hiddendangerRecordDtoLists);
            }
            //审核信息
            List<NoticeBookAuditDomain> noticeBookAuditDomain = noticeBookAuditRepository.findByNoticeNo(noticeBookdb.getNoticeNo());
            if (null != noticeBookAuditDomain && !noticeBookAuditDomain.isEmpty()) {
                List<NoticeBookAuditDto> noticeBookAuditDtos = BeanMapper.mapList(noticeBookAuditDomain, NoticeBookAuditDto.class);
                nBDetailDto.setNoticeBookAuditDtoList(noticeBookAuditDtos);
            }

            String nBDetailDtoJson = JsonMapper.defaultMapper().toJson(nBDetailDto);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");
            resDto.setDatas(nBDetailDtoJson);
            return resDto;
        } catch (Exception e) {
            log.error("对象转化异常");
            return new ResDto(Const.SERVER_ERROR, "数据解析异常");
        }

    }

    /**
     * 生成整改报告的查询的数据是[通知书详情]的代码
     *
     * @param id
     * @return
     */
    @Override
    public ResDto generateReportNoticeBookById(String id) {
        NoticeBookDomain noticeBookdb = null;
        if (StringUtils.isNotBlank(id)) {
            noticeBookdb = noticeBookRepository.findOne(id);
            if (noticeBookdb == null) {
                return new ResDto(Const.DATA_ERROR, "id不存在");
            }
        }

        NoticeBookExportWordDto nBWordDto = new NoticeBookExportWordDto();
        //基本信息
        NoticeBookReturnDto noticeBookDto = BeanMapper.map(noticeBookdb, NoticeBookReturnDto.class);
        nBWordDto.setNoticeBookDto(noticeBookDto);
        //隐患记录
        List<String> hiddenDangerIds = noticeBookdb.getHiddenDangerIds();
        List<HiddendangerRecordDto> hiddendangerRecordDtoLists = null;
        if (null != hiddenDangerIds && !hiddenDangerIds.isEmpty()) {
            Iterable<HiddendangerRecord> all = hiddenDangerRecordRepository.findAll(hiddenDangerIds);
            hiddendangerRecordDtoLists = BeanMapper.mapList(all, HiddendangerRecordDto.class);
            //nBDetailDto.setHiddenDangerRecordList(hiddendangerRecordDtoLists);
        }

        //院系级隐患
        List<HiddendangerRecordDto> unitRecords = new ArrayList<HiddendangerRecordDto>();
        //实验室级隐患
        List<HiddendangerRecordDto> labRecords = new ArrayList<HiddendangerRecordDto>();
        //实验室集合--可以看到有几个实验室
        List<LaboratoryDto> laboratoryDtoList = new ArrayList<>();
        if (null != hiddendangerRecordDtoLists && hiddendangerRecordDtoLists.size() > 0) {
            for (int i = 0; i < hiddendangerRecordDtoLists.size(); i++) {
                HiddendangerRecordDto oneDto = hiddendangerRecordDtoLists.get(i);

                List<RectifyReviewDto> zgList = rectifyReviewRepositoryImpl.findRectifyReview(oneDto.getId(), "0", RectifyReviewDomain.class, RectifyReviewDto.class);
                //查最新的整改信息
                List<RectifyReviewDto> fcList = rectifyReviewRepositoryImpl.findRectifyReview(oneDto.getId(), "1", RectifyReviewDomain.class, RectifyReviewDto.class);

                if (null != zgList && zgList.size() > 0) {
                    RectifyReviewDto zgDto = zgList.get(0);
                    //有图片,转成Base64
                    RectifyReviewDto zgBase64Dto = zgfcPicPathToBase64(zgDto);
                    oneDto.setZhengGaiInfo(zgBase64Dto);
                }
                if (null != fcList && fcList.size() > 0) {
                    RectifyReviewDto fcDto = fcList.get(0);
                    //有图片,转成Base64
                    RectifyReviewDto fcBase64Dto = zgfcPicPathToBase64(fcDto);
                    oneDto.setFuChaInfo(fcBase64Dto);
                }

                /**查询是否有院系或实验室的隐患记录**/
                /**区分院系和实验室隐患记录对象**/
                String checkId = oneDto.getCheckId();
                CheckRecord checkRecordDomain = checkRecordsRepository.findOne(checkId);
                //综合隐患
                if (null != checkRecordDomain && checkRecordDomain.getCheckType().equals("0")) {
                    HiddendangerRecordDto oneBase64Dto = picPathToBase64(oneDto);
                    unitRecords.add(oneBase64Dto);
                }
                //实验室隐患
                if (null != checkRecordDomain && checkRecordDomain.getCheckType().equals("1")) {
                    String checkLabId = oneDto.getCheckLabId();
                    //查出已经配置的危险源检查项的一级名称
                    if (StringUtils.isNotBlank(checkLabId)) {
                        LaboratoryDomain labDomain = laboratoryRepository.findOne(checkLabId);

                        //得到一级的检查项名称
                        List<String> labInspectItemNames = new ArrayList<>();
                        //先查关系表
                        List<LabInspectItemRelationDomain> relationDomains = labInspectItemRelationRepository.findByLabId(checkLabId);
                        if (null != relationDomains && relationDomains.size() > 0) {
                            for (int m = 0; m < relationDomains.size(); m++) {
                                String inspectItemId = relationDomains.get(m).getInspectItemId();
                                //再查检查项表
                                LabInspectItemTreeDomain item = labInspectItemTreeRepository.findOne(inspectItemId);
                                if (item.getItemLevel().equals("1")) {
                                    //检查项类型是危险源：item_category为0
                                    if (item.getItemCategory().equals("0")) {
                                        String itemName = item.getItemName();
                                        if (!labInspectItemNames.contains(itemName)) {
                                            labInspectItemNames.add(itemName);
                                        }
                                    }
                                } else {
                                    LabInspectItemTreeDomain item2 = labInspectItemTreeRepository.findOne(item.getItemParentId());
                                    if (item2.getItemCategory().equals("0")) {
                                        String itemName2 = item2.getItemName();
                                        if (!labInspectItemNames.contains(itemName2)) {
                                            labInspectItemNames.add(itemName2);
                                        }
                                    }
                                }
                            }
                        }

                        //危险源检查项的一级名称添加到隐患中
                        StringBuffer buffer = null;
                        if (labInspectItemNames.size() > 0) {
                            buffer = new StringBuffer();
                            for (String nameStr : labInspectItemNames) {
                                buffer.append(nameStr).append(";");
                            }
                            oneDto.setLabInspectItemNameStrs(buffer.toString());
                        }

                        //实验室信息对象添加到隐患中
                        if (null != labDomain) {
                            LaboratoryDto labDto = BeanMapper.map(labDomain, LaboratoryDto.class);
                            oneDto.setLaboratory(labDto);

                            //实验室集合--(防止同一个实验室的隐患显示多条实验室信息)
                            if (laboratoryDtoList.size() > 0) {
                                for (LaboratoryDto lablab : laboratoryDtoList) {
                                    if (!lablab.getId().equals(labDto.getId())) {
                                        //危险源检查项的一级名称添加到实验室中去
                                        labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
                                        laboratoryDtoList.add(labDto);
                                    }
                                }
                            } else {
                                //危险源检查项的一级名称添加到实验室中去
                                labDto.setLabInspectItemNameStrs(buffer == null ? "" : buffer.toString());
                                laboratoryDtoList.add(labDto);
                            }
                        }
                    }
                    HiddendangerRecordDto oneBase64Dto = picPathToBase64(oneDto);
                    labRecords.add(oneBase64Dto);
                }
            }
        }

        nBWordDto.setUnitRecords(unitRecords);
        nBWordDto.setLabRecords(labRecords);
        nBWordDto.setLabList(laboratoryDtoList);

        //生成word整改报告
        Map<String, Object> datasMap = new HashMap<String, Object>(4);
        datasMap.put("nBWordDto", nBWordDto);

//        //通知书编号
//        datasMap.put("noticeBookNo", "+"+noticeBookDto.getNoticeNo());
//        //院系
//        datasMap.put("unitName", noticeBookDto.getNoticeReceiveUnit());
//        //所室
//        datasMap.put("offices", "");
//        //通知书下发时间
//        datasMap.put("sendDate", DateFormatUtil.formatDate("yyyy年MM月dd日", noticeBookDto.getNoticeSendDate()));

//        //判断是否显示院系级的隐患
//        datasMap.put("unitHiddenDangerIDList", unitHiddenDangerIDList);
//        //判断是否显示实验室级的隐患
//        datasMap.put("labHiddenDangerIDList", labHiddenDangerIDList);
//        if (null != unitHiddenDangerIDList && unitHiddenDangerIDList.size() > 0) {
//            datasMap.put("unitHiddenDangerRecords", unitRecords);
//        }
//        if (null != labHiddenDangerIDList && labHiddenDangerIDList.size() > 0) {
//            datasMap.put("labHiddenDangerRecords", labRecords);
//        }

//        datasMap.put("gmt_created", "2017-12-10 08:12:56");
//        datasMap.put("hiddendesc", "123456789");
//        datasMap.put("image_url", "123");
//        datasMap.put("desc", "123");
//        datasMap.put("create_user_name", "123");
//        datasMap.put("submit_user_name", "张三李四");
//        datasMap.put("submit_time", "123");
//        datasMap.put("building_name", "123");
//        datasMap.put("room_no", "123");
//        datasMap.put("lab_name", "123");
//        datasMap.put("risk_manager", "王强");
//        datasMap.put("risk_level", "B");

        // /生成word文档
        DocumentHandler documentHandler = new DocumentHandler();
        ResDto resDto = new ResDto();
        try {
        /**导出doc2003代码 start**/
            //本地测试代码
            //long time = new Date().getTime();
            //documentHandler.createDoc("template_noticebook.ftl", datasMap, "E:/noticebook" + (time) + ".docx");
            //documentHandler.createDoc("template_noticebook.ftl",datasMap, "E:/noticebook.doc");
            //documentHandler.createNewWordDoc("E:/noticebook" + (time) + ".doc","E:/noticebook" + (time) + "_new.doc");
            //documentHandler.convertDocxToPDF("E:/AQZG_jhq333333333.docx","E:/AQZG_jhq333333333_new.pdf");

//            //拼接服务器上的路径地址
//            String path = "/word/";
//            String roleId = "1";
//            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
//            path += roleId + "/" + date + "/";
//            //保存文件
//            String noticeBookFilepath = filePath + path;
//            File dir = new File(noticeBookFilepath);
//            //File dir = new File(path);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            //保存word的地址
//            String saveFileNameAndPath = noticeBookFilepath + nBWordDto.getNoticeBookDto().getNoticeNo() + ".doc";
//            documentHandler.createDoc("template_noticebook.ftl", datasMap, saveFileNameAndPath);
//            //documentHandler.createNewWordDoc(saveFileNameAndPath,noticeBookFilepath + nBWordDto.getNoticeBookDto().getNoticeNo() + "_new.doc");
//            resDto.setStatus(Const.SUCCESS);
//            resDto.setMsg("成功");
//            //下载word的地址
//            String downLoadFileNameAndPath = urlPath + path + nBWordDto.getNoticeBookDto().getNoticeNo() + ".doc";
//            resDto.setDatas(downLoadFileNameAndPath);
            /**导出doc2003代码 end**/

            /**导出doc2013代码 start**/
//            //本地测试代码
//            File resumeFile = WordTools.createDoc("D:\\word\\test.xml", datasMap, "noticebook_2013.ftl");
//            WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) WordprocessingMLPackage.load(new FileInputStream(resumeFile));
//            File file = new File("D:\\word\\noticebook.docx");
//            wmlPackage.save(file, Docx4J.FLAG_SAVE_ZIP_FILE);


            //拼接服务器上的路径地址
            String path = "/word/";
            String roleId = "1";
            String date = DateFormatUtil.formatDate(DateFormatUtil.PATTERN_ISO_ON_DATE, new Date());
            path += roleId + "/" + date + "/";
            //保存文件
            String noticeBookFilepath = filePath + path;
            File dir = new File(noticeBookFilepath);
            //File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //保存word的地址
            //documentHandler.createDoc("template_noticebook.ftl", datasMap, saveFileNameAndPath);
            File resumeFile = WordTools.createDoc("template_noticebook_2013.xml", datasMap, "template_noticebook_2013.ftl");
            WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) WordprocessingMLPackage.load(new FileInputStream(resumeFile));
//            File file = new File(saveFileNameAndPath);
            String objectId= new ObjectId().toString();
            FileOutputStream fos =new FileOutputStream(
                    java.text.Normalizer.normalize(
                            "/var/www/images/qh" + path + objectId + ".docx"
                            , java.text.Normalizer.Form.NFKD)
            );
            wmlPackage.save(fos, Docx4J.FLAG_SAVE_ZIP_FILE);

            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");
            //下载word的地址
            String downLoadFileNameAndPath = urlPath + path + objectId + ".docx";
            resDto.setDatas(downLoadFileNameAndPath);

            /**导出doc2013代码 end**/
        } catch (Exception e) {//UnsupportedEncodingException e
            e.printStackTrace();
            resDto.setStatus(Const.DATA_ERROR);
            resDto.setMsg("生成报告异常");
        }
        return resDto;
    }

    /**
     * 隐患图片转成Base64编码
     *
     * @param hiddendangerRecord
     */
    public HiddendangerRecordDto picPathToBase64(HiddendangerRecordDto hiddendangerRecord) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = hiddendangerRecord.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());

                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        hiddendangerRecord.setUploadImageBase64(base64List);
        return hiddendangerRecord;
    }

    /**
     * 整改复查图片转成Base64编码
     *
     * @param rectifyReviewDto
     */
    public RectifyReviewDto zgfcPicPathToBase64(RectifyReviewDto rectifyReviewDto) {
        //隐患记录中的图片
        List<UploadImage> uploadImageList = rectifyReviewDto.getUploadImageList();
        List<UploadImageBase64Bean> base64List = new ArrayList<>();
        if (null != uploadImageList && uploadImageList.size() > 0) {
            for (int j = 0; j < uploadImageList.size(); j++) {
                //图片地址转成Base64
                UploadImage uploadImageconvert = new UploadImage();
                //类型转换
                BeanUtils.copyProperties(uploadImageList.get(j), uploadImageconvert);
                if (StringUtils.isNotBlank(uploadImageconvert.getPath())) {
                    //网络获取图片
                    String base64PicStr = Base64Util.GetImageStrFromUrl(urlPath + uploadImageconvert.getPath());

                    UploadImageBase64Bean base64Bean = new UploadImageBase64Bean();
                    base64Bean.setUploadImageBase64(base64PicStr);
                    base64Bean.setPicId(IdGenerator.uuid2());
                    base64List.add(base64Bean);
                }
            }
        }
        rectifyReviewDto.setUploadImageBase64(base64List);
        return rectifyReviewDto;
    }

    @Override
    public ResDto addNoticeBookAudit(HttpServletRequest request, NoticeBookAuditDto noticeBookAuditDto) {
        try {
            String token = request.getHeader(Const.TOKEN_NAME);
            UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
            if (userSessionDTO == null) {
                return new ResDto(Const.PARAM_ERROR, "用户未登录");
            }
            //验证参数
            if (StringUtils.isBlank(userSessionDTO.getId())) {
                return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
            }

            String noticeNo = noticeBookAuditDto.getNoticeNo();
            String noticeAuditResult = noticeBookAuditDto.getNoticeAuditResult();

            //处理状态已经变更就不能再操作了(只要是已经是： 3认可 和 1通过，就不能再进行修改了)
            NoticeBookDomain byNoticeNo = noticeBookRepository.findByNoticeNo(noticeNo);
            List<NoticeBookAuditDomain> shenheTongguo = noticeBookAuditRepository.findByNoticeNoAndNoticeAuditResult(noticeNo, "1");
            if (null != shenheTongguo && shenheTongguo.size() > 0) {//3：表示已经下发
                if (!byNoticeNo.getNoticeStatus().equals("3")) {
                    return new ResDto(Const.SERVER_ERROR, "审核已经通过,不能重复操作");
                }
            }
            List<NoticeBookAuditDomain> fanganRenke = noticeBookAuditRepository.findByNoticeNoAndNoticeAuditResult(noticeNo, "3");
            if (null != fanganRenke && fanganRenke.size() > 0) {
                return new ResDto(Const.SERVER_ERROR, "方案已经认可,不能重复操作");
            }
            NoticeBookAuditDomain noticeBookAuditDomain = BeanMapper.map(noticeBookAuditDto, NoticeBookAuditDomain.class);
            noticeBookAuditDomain.setId(IdGenerator.uuid2());
            noticeBookAuditDomain.setNoticeAuditorId(userSessionDTO.getId());
            noticeBookAuditDomain.setNoticeAuditorName(userSessionDTO.getNickname());
            noticeBookAuditDomain.setGmtCreated(new Date());
            noticeBookAuditDomain.setGmtModified(new Date());

            NoticeBookAuditDomain save = noticeBookAuditRepository.save(noticeBookAuditDomain);
            //成功后还要修改通知书表的状态
            NoticeBookDomain noticeBookDomain =
                    noticeBookRepository.findByNoticeNo(noticeBookAuditDomain.getNoticeNo());

            if (noticeBookAuditDomain.getNoticeAuditSource().equals(CommonDbConst.NOTICESOURCE_NOTICE)) {
                //修改通知书状态
                noticeBookDomain.setNoticeStatus(noticeBookAuditDomain.getNoticeAuditResult());
            } else if (noticeBookAuditDomain.getNoticeAuditSource().equals(CommonDbConst.NOTICESOURCE_CASE)) {
                //修改通知书方案状态
                if (noticeBookAuditDomain.getNoticeAuditResult().equals(CommonDbConst.NOTICEAUDIT_CASE_PASS)) {
                    noticeBookDomain.setNoticeCaseStatus("2");
                } else if (noticeBookAuditDomain.getNoticeAuditResult().equals(CommonDbConst.NOTICEAUDIT_CASE_UNPASS)) {
                    noticeBookDomain.setNoticeCaseStatus("3");
                }
            }
            noticeBookRepository.save(noticeBookDomain);


            if (save == null) {
                log.info("通知书审核信息添加失败");
                return new ResDto(Const.SERVER_ERROR, "通知书审核信息添加失败");
            }
            return new ResDto(Const.SUCCESS, "通知书审核信息添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "数据处理异常");
        }

    }

    @Override
    public ResDto addNoticeBookCaseInfo(HttpServletRequest request, List<HiddendangerRecordDto> hiddendangerRecordDtoList) {
        String noticeNo = null;
        try {
            String token = request.getHeader(Const.TOKEN_NAME);
            UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
            if (userSessionDTO == null) {
                return new ResDto(Const.PARAM_ERROR, "用户未登录");
            }
            //验证参数
            if (StringUtils.isBlank(userSessionDTO.getId())) {
                return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
            }

            for (HiddendangerRecordDto hiddendangerRecordDto : hiddendangerRecordDtoList) {
                String id = hiddendangerRecordDto.getId();
                if (!StringUtils.isNotBlank(noticeNo)) {
                    noticeNo = hiddendangerRecordDto.getNoticeNo();
                }
                HiddendangerRecord hiddendangerRecordDomain = hiddenDangerRecordRepository.findOne(id);
                if (null == hiddendangerRecordDomain) {
                    return new ResDto(Const.SERVER_ERROR, "隐患记录id不存在");
                }
                hiddendangerRecordDomain.setPreTime(hiddendangerRecordDto.getPreTime());
                hiddendangerRecordDomain.setCaseMethod(hiddendangerRecordDto.getCaseMethod());

                hiddendangerRecordDomain.setCaseUserNameId(userSessionDTO.getId());
                hiddendangerRecordDomain.setCaseGmtCreate(new Date());
                UserInfo userInfo = userInfoRepository.findOne(userSessionDTO.getId());
                if (userInfo != null) {
                    hiddendangerRecordDomain.setCaseUserName(userInfo.getFullName());
                }
                hiddenDangerRecordRepository.save(hiddendangerRecordDomain);
            }
            //修改通知书的状态
            NoticeBookDomain noticeBookDomain = noticeBookRepository.findByNoticeNo(noticeNo);
            noticeBookDomain.setNoticeCaseStatus("1");
            NoticeBookDomain save1 = noticeBookRepository.save(noticeBookDomain);
            if (save1 == null) {
                log.info("整改方案修改状态失败");
                return new ResDto(Const.SERVER_ERROR, "整改方案修改状态失败");
            }
            ResDto resDto = new ResDto(Const.SUCCESS, "通知书整改方案添加成功");
            resDto.setDatas(null);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "数据处理异常");
        }

    }

    @Override
    public ResDto updateNoticeBookCaseInfo(HttpServletRequest request, List<HiddendangerRecordDto> hiddendangerRecordDtoList) {
        //NoticeCaseStatus: 0未提交 1已提交 2认可方案 3不认可方案
        String noticeNo = null;
        try {
            String token = request.getHeader(Const.TOKEN_NAME);
            UserSessionDTO userSessionDTO = iSessionService.getSessionByToken(token);
            if (userSessionDTO == null) {
                return new ResDto(Const.PARAM_ERROR, "用户未登录");
            }
            //验证参数
            if (StringUtils.isBlank(userSessionDTO.getId())) {
                return new ResDto(Const.SERVER_ERROR, "获取用户id失败");
            }

            for (HiddendangerRecordDto hiddendangerRecordDto : hiddendangerRecordDtoList) {
                String id = hiddendangerRecordDto.getId();
                HiddendangerRecord hiddendangerRecordDomain = hiddenDangerRecordRepository.findOne(id);
                if (!StringUtils.isNotBlank(noticeNo)) {
                    noticeNo = hiddendangerRecordDto.getNoticeNo();
                }
                if (null == hiddendangerRecordDomain) {
                    return new ResDto(Const.SERVER_ERROR, "隐患记录id不存在");
                }
                hiddendangerRecordDomain.setPreTime(hiddendangerRecordDto.getPreTime());
                hiddendangerRecordDomain.setCaseMethod(hiddendangerRecordDto.getCaseMethod());
                hiddenDangerRecordRepository.save(hiddendangerRecordDomain);
            }
            //修改通知书的状态:1 已提交
            NoticeBookDomain noticeBookDomain = noticeBookRepository.findByNoticeNo(noticeNo);
            noticeBookDomain.setNoticeCaseStatus("1");
            NoticeBookDomain save1 = noticeBookRepository.save(noticeBookDomain);
            if (save1 == null) {
                log.info("整改方案修改状态失败");
                return new ResDto(Const.SERVER_ERROR, "整改方案修改状态失败");
            }
            ResDto resDto = new ResDto(Const.SUCCESS, "通知书整改方案修改成功");
            resDto.setDatas(null);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "数据处理异常");
        }

    }


    /**
     * 获取通知书方案详情
     *
     * @param id
     * @return
     */
    @Override
    public ResDto getNoticeBookCaseInfo(String id) {
        try {
            //获取到隐患记录hidden_danger_ids
            //再查（隐患id和通知书编号相同）整改方案
            NoticeBookDomain noticeBookdb = null;
            if (StringUtils.isNotBlank(id)) {
                noticeBookdb = noticeBookRepository.findOne(id);
                if (noticeBookdb == null) {
                    return new ResDto(Const.DATA_ERROR, "通知书id不存在");
                }
            }
            NoticeBookDetailDto nBDetailDto = new NoticeBookDetailDto();
            //基本信息
            NoticeBookReturnDto noticeBookDto = BeanMapper.map(noticeBookdb, NoticeBookReturnDto.class);
            if (StringUtils.isNotBlank(noticeBookDto.getNoticeAttachPath())) {
                noticeBookDto.setNoticeAttachPath(urlPath + noticeBookDto.getNoticeAttachPath());
            }
            nBDetailDto.setNoticeBookDto(noticeBookDto);

            //隐患记录
            List<String> hiddenDangerIds = noticeBookdb.getHiddenDangerIds();
            if (null != hiddenDangerIds && !hiddenDangerIds.isEmpty()) {
                Iterable<HiddendangerRecord> all = hiddenDangerRecordRepository.findAll(hiddenDangerIds);
                List<HiddendangerRecordDto> hiddendangerRecordDtoLists = BeanMapper.mapList(all, HiddendangerRecordDto.class);
                nBDetailDto.setHiddenDangerRecordList(hiddendangerRecordDtoLists);
            }

            //审核信息
            List<NoticeBookAuditDomain> noticeBookCaseAudit = noticeBookAuditRepository.findByNoticeNoAndNoticeAuditSource(noticeBookdb.getNoticeNo(), "2");
            if (null != noticeBookCaseAudit && !noticeBookCaseAudit.isEmpty()) {
                List<NoticeBookAuditDto> noticeBookAuditDtos = BeanMapper.mapList(noticeBookCaseAudit, NoticeBookAuditDto.class);
                nBDetailDto.setNoticeBookAuditDtoList(noticeBookAuditDtos);
            }

            String nBDetailDtoJson = JsonMapper.defaultMapper().toJson(nBDetailDto);
            ResDto resDto = new ResDto();
            resDto.setStatus(Const.SUCCESS);
            resDto.setMsg("成功");
            resDto.setDatas(nBDetailDtoJson);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据处理异常");
            return new ResDto(Const.SERVER_ERROR, "数据处理异常");
        }

    }

    /**
     * 生成通知书的PDF
     *
     * @return
     */
    @Override
    public String saveNoticePdf(String noticeID) {
        Map<String, Object> variables = new HashMap<String, Object>(3);

        List<NoticeBookDetailDto> noticeBookDetailDtoList = new ArrayList<NoticeBookDetailDto>();

        ResDto resDto =
                getNoticeBookById(noticeID);

        NoticeBookDetailDto noticeBookDetailDto =
                JsonMapper.defaultMapper().fromJson(resDto.getDatas(), NoticeBookDetailDto.class);


        noticeBookDetailDtoList.add(noticeBookDetailDto);


//            variables.put("title", "用户列表");
        variables.put("noticeBookDetailDtoList", noticeBookDetailDtoList);

        if (noticeBookDetailDtoList.size() > 0) {
            String fileName = noticeBookDetailDtoList.get(0).getNoticeBookDto().getNoticeNo() + ".pdf";
            String id = commonService.savePdfByNotice("1", fileName, "2", variables, "");
            return id;
        }
        return null;
    }

}
